<script lang="ts" setup>
import {
  IconEye,
  VModal,
  VSpace,
  VTag,
  VCard,
  VAvatar,
  VDescription,
  VDescriptionItem,
  VStatusDot,
} from "@halo-dev/components";
import { FormKit } from "@formkit/vue";
import { computed, onMounted, ref, watch } from "vue";
import type { Product, ProductType } from "@console/types";
import { productTypeApiClient } from "@console/api/product";
import { formatDatetime } from "@console/utils/date";

// 定义window对象
const windowObj = typeof window !== 'undefined' ? window : null;

const props = withDefaults(
  defineProps<{
    visible: boolean;
    product?: Product;
  }>(),
  {
    visible: false,
    product: undefined,
  }
);

const emit = defineEmits<{
  "update:visible": [visible: boolean];
  "close": [];
}>();

const productTypes = ref<ProductType[]>([]);
const currentProductType = ref<ProductType>();

const handleVisibleChange = (visible: boolean) => {
  emit("update:visible", visible);
  if (!visible) {
    emit("close");
  }
};

const handleFetchProductTypes = async () => {
  try {
    const { data } = await productTypeApiClient.listProductTypes({
      page: 0,
      size: 0,
    });
    productTypes.value = data.items;
  } catch (error) {
    console.error("Failed to fetch product types", error);
  }
};

const getProductTypeName = (productTypeRef: string) => {
  const productType = productTypes.value.find(
    (type) => type.metadata.name === productTypeRef
  );
  return productType?.spec.displayName || productTypeRef;
};

const formatPrice = (price?: number) => {
  if (price === undefined || price === null) return "-";
  return `¥${price.toFixed(2)}`;
};

const openImageInNewTab = (imageUrl: string) => {
  if (typeof window !== 'undefined' && window.open) {
    window.open(imageUrl, '_blank');
  }
};

watch(
  () => props.product,
  (product) => {
    if (product) {
      currentProductType.value = productTypes.value.find(
        (type) => type.metadata.name === product.spec.productTypeRef
      );
    }
  }
);

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      handleFetchProductTypes();
    }
  }
);

onMounted(handleFetchProductTypes);
</script>

<template>
  <VModal
    :visible="visible"
    :width="800"
    title="产品详情"
    :centered="false"
    @update:visible="handleVisibleChange"
  >
    <div v-if="product" class="space-y-6">
      <!-- 基本信息 -->
      <VCard>
        <template #header>
          <div class="flex items-center gap-2">
            <IconEye class="h-4 w-4" />
            <span class="font-medium">基本信息</span>
          </div>
        </template>
        <VDescription>
          <VDescriptionItem label="产品名称">
            <div class="flex items-center gap-2">
              <span>{{ product.spec.displayName }}</span>
              <VStatusDot
                v-if="product.spec.published"
                state="success"
                text="已发布"
              />
              <VStatusDot
                v-else
                state="default"
                text="未发布"
              />
            </div>
          </VDescriptionItem>
          <VDescriptionItem label="产品类型">
            <VTag>{{ getProductTypeName(product.spec.productTypeRef) }}</VTag>
          </VDescriptionItem>
          <VDescriptionItem label="产品描述">
            <div class="whitespace-pre-wrap">
              {{ product.spec.description || '暂无描述' }}
            </div>
          </VDescriptionItem>
          <VDescriptionItem label="优先级">
            {{ product.spec.priority || 0 }}
          </VDescriptionItem>
          <VDescriptionItem label="创建时间">
            {{ formatDatetime(product.metadata.creationTimestamp) }}
          </VDescriptionItem>
          <VDescriptionItem v-if="product.metadata.labels" label="标签">
            <VSpace>
              <VTag
                v-for="(value, key) in product.metadata.labels"
                :key="key"
                size="sm"
              >
                {{ key }}: {{ value }}
              </VTag>
            </VSpace>
          </VDescriptionItem>
        </VDescription>
      </VCard>

      <!-- 产品图片 -->
      <VCard v-if="product.spec.images?.length">
        <template #header>
          <div class="flex items-center gap-2">
            <IconEye class="h-4 w-4" />
            <span class="font-medium">产品图片</span>
          </div>
        </template>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div
            v-for="(image, index) in product.spec.images"
            :key="index"
            class="relative group cursor-pointer"
            @click="() => openImageInNewTab(image)"
          >
            <VCard class="p-2 hover:shadow-md transition-shadow">
              <VAvatar
                :src="image"
                :alt="`产品图片 ${index + 1}`"
                size="lg"
                class="w-full h-24 object-cover"
              />
            </VCard>
          </div>
        </div>
      </VCard>

      <!-- 价格信息 -->
      <VCard>
        <template #header>
          <div class="flex items-center gap-2">
            <IconEye class="h-4 w-4" />
            <span class="font-medium">价格信息</span>
          </div>
        </template>
        <VDescription>
          <VDescriptionItem label="单价">
            <span class="text-lg font-semibold text-green-600">
              {{ formatPrice(product.spec.price) }}
            </span>
          </VDescriptionItem>
          <VDescriptionItem v-if="product.spec.samplePrice" label="样品价格">
            <span class="text-lg font-semibold text-blue-600">
              {{ formatPrice(product.spec.samplePrice) }}
            </span>
          </VDescriptionItem>
          <VDescriptionItem v-if="product.spec.minOrderQuantity" label="最低起订量">
            <span class="font-medium">
              {{ product.spec.minOrderQuantity }} 件
            </span>
          </VDescriptionItem>
        </VDescription>
      </VCard>

      <!-- 技术信息 -->
      <VCard>
        <template #header>
          <div class="flex items-center gap-2">
            <IconEye class="h-4 w-4" />
            <span class="font-medium">技术信息</span>
          </div>
        </template>
        <VDescription>
          <VDescriptionItem label="资源名称">
            {{ product.metadata.name }}
          </VDescriptionItem>
          <VDescriptionItem label="API 版本">
            {{ product.apiVersion }}
          </VDescriptionItem>
          <VDescriptionItem label="资源类型">
            {{ product.kind }}
          </VDescriptionItem>
          <VDescriptionItem v-if="product.status?.observedVersion" label="观察版本">
            {{ product.status.observedVersion }}
          </VDescriptionItem>
          <VDescriptionItem v-if="product.status?.permalink" label="永久链接">
            <a
              :href="product.status.permalink"
              target="_blank"
              class="text-blue-600 hover:text-blue-800 underline"
            >
              {{ product.status.permalink }}
            </a>
          </VDescriptionItem>
        </VDescription>
      </VCard>
    </div>
  </VModal>
</template>